<?php

$method = $_GET['m'] ?? '';

if ($method == 'add') {
    add();
}

if ($method == 'del') {
    del($_GET['item']);
}

$data = getFile();

json([
    'list'        => $data,
    'total'       => count($data),
    'total_ten'   => count(array_filter($data, fn($item) => time() - strtotime($item) < 86400 * 10)),
    'total_month' => count(array_filter($data, fn($item) => time() - strtotime($item) < 86400 * 30)),
    'total_year'  => count(array_filter($data, fn($item) => time() - strtotime($item) < 86400 * 365)),
    'last'        => formatDateDistance($data[count($data) - 1] ?? ''),
    'group_month' => lastYearGroupByMonth($data),
]);

function lastYearGroupByMonth($data)
{
    $list = [];

    foreach ($data as $item) {
        $month        = date('Y-m', strtotime($item));
        $list[$month] = [
            'month' => $month,
            'count' => ($list[$month]['count'] ?? 0) + 1,
        ];
    }

    return array_values($list);
}

function formatDateDistance($date)
{
    $date     = $date ?: date('Y-m-d H:i:s');
    $distance = time() - strtotime($date);
    $day      = floor($distance / 86400);
    $hour     = floor(($distance % 86400) / 3600);
    $minute   = floor(($distance % 3600) / 60);
    $second   = $distance % 60;
    $str      = '';
    if ($day) {
        $str .= $day . '天';
    }
    if ($hour) {
        $str .= $hour . '小时';
    }
    if ($minute) {
        $str .= $minute . '分钟';
    }
    $str .= $second . '秒';
    return $str;
}

function getFile()
{
    return json_decode(@file_get_contents(__DIR__ . '/data.json'), true) ?? [];
}

function putFile($data)
{
    file_put_contents(__DIR__ . '/data.json', json_encode(array_values($data)));
}

function add()
{
    $file   = getFile();
    $file[] = date('Y-m-d H:i:s');
    putFile($file);
}

function del($item)
{
    $file = getFile();

    foreach ($file as $key => $value) {
        if ($value == $item) {
            unset($file[$key]);
        }
    }

    putFile($file);
}

function json($data)
{
    echo json_encode($data);
    exit;
}
